const Router = require('koa-router')
const db = require('../db')
const config = require('../config')  // 添加这行

const router = new Router({ prefix: '/api/bookings' })

// 获取预约历史列表保持不变，因为已经使用了正确的表名和结构
router.get('/', async (ctx) => {
  try {
    // 从请求参数中获取用户ID，如果未提供则默认为1（用于开发测试）
    const userId = ctx.query.userId || 1;
    
    const bookings = await db.executeQuery(`
      SELECT 
        b.*,
        c.title as course_name,
        c.image_url as cover,
        t.name as teacher_name,
        DATE_FORMAT(b.booking_date, '%Y-%m-%d') as formatted_date,
        b.time_slot as course_time,
        b.contact_name,
        b.contact_phone,
        b.status,
        b.is_rated,
        cc.rating,  -- 新增评价分数
        cc.content as comment  -- 新增评价内容
      FROM bookings b
      LEFT JOIN courses c ON b.course_id = c.id
      LEFT JOIN teachers t ON c.teacher_id = t.id
      LEFT JOIN course_comments cc ON b.id = cc.booking_id  -- 新增联表查询
      WHERE b.user_id = ?
      ORDER BY b.created_at DESC
    `, [userId])

    // 处理图片URL
    const processedBookings = bookings.map(booking => ({
      ...booking,
      cover: booking.cover ? `${config.development.baseURL}${booking.cover}` : ''
    }))

    ctx.body = { code: 200, data: processedBookings }
  } catch (error) {
    console.error('获取预约历史失败:', error)
    ctx.status = 500
    ctx.body = { code: 500, message: '获取预约历史失败' }
  }
})

// 添加积分的辅助函数
const addPoints = async (userId, courseId, toastInfo) => {
  const points = courseId ?? 10 // 每次预约获得10积分
  await db.executeQuery(
    'INSERT INTO points_history (user_id, amount, type, title) VALUES (?, ?, "earn", ?)',
    [userId, points, toastInfo]
  )
}

// 创建预约
router.post('/create', async (ctx) => {
  const { course_id, booking_date, time_slot, contact_name, contact_phone, remark, userId } = ctx.request.body
  // 使用请求中的用户ID，如果未提供则默认为1（用于开发测试）
  const userIdToUse = userId || 1;
  // 预约课程新增的积分，常量写死：根据产品逻辑调整
  const POINTS = 10;

  console.log('创建预约请求参数:', {
    course_id,
    booking_date,
    time_slot,
    contact_name,
    contact_phone,
    remark,
    userId,
    userIdToUse
  });

  // 使用事务来确保数据一致性
  const conn = await db.pool.getConnection()
  await conn.beginTransaction()

  try {
    // 检查该时段是否已被预约
    const [existingBookings] = await conn.query(  // 这里解构第一个数组
      `SELECT id FROM bookings 
       WHERE course_id = ? 
       AND booking_date = ? 
       AND time_slot = ? 
       AND status != 'cancelled'`,
      [course_id, booking_date, time_slot]
    )

    console.log('查询预约结果:', {
      course_id,
      booking_date,
      time_slot,
      userIdToUse,
      existingBookings
    })

    // 如果查询结果有记录，说明该时段已被预约
    if (existingBookings && existingBookings.length > 0) {
      await conn.rollback()
      ctx.status = 400
      ctx.body = { code: 400, message: '该时段已被预约' }
      return
    }

    // 生成订单编号：当前时间戳+随机数
    const timestamp = Date.now().toString();
    const randomNum = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
    const bookingNumber = `BK${timestamp}${randomNum}`;
    
    // 获取课程价格
    const [courseResult] = await conn.query('SELECT price FROM courses WHERE id = ?', [course_id]);
    const coursePrice = courseResult[0]?.price || 0;

    // 创建预约记录
    const result = await conn.query(
      `INSERT INTO bookings (
        booking_number, course_id, user_id, booking_date, time_slot, 
        contact_name, contact_phone, remark, status, payment_method,
        transaction_id, amount
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'upcoming', 'wechat', ?, ?)`,
      [bookingNumber, course_id, userIdToUse, booking_date, time_slot, 
       contact_name, contact_phone, remark, `wx_${timestamp}`, coursePrice]
    )

    console.log('创建预约结果:', {
      insertId: result[0]?.insertId,
      userIdToUse,
      course_id,
      bookingNumber
    });

    // 更新课程预约人数
    await conn.query(
      'UPDATE courses SET enroll_count = enroll_count + 1 WHERE id = ?',
      [course_id]
    )

    // 添加积分记录
    await addPoints(userIdToUse, POINTS, '预约课程奖励')

    // 提交事务
    await conn.commit()

    ctx.body = { 
      code: 200, 
      message: '预约成功', 
      booking_id: result[0]?.insertId,
      booking_number: bookingNumber
    }
  } catch (error) {
    // 发生错误时回滚事务
    await conn.rollback()
    console.error('创建预约失败:', error)
    ctx.status = 500
    ctx.body = { code: 500, message: '服务器内部错误' }
  } finally {
    // 释放连接
    conn.release()
  }
})

// 新增评价接口（修正版）
router.post('/rate', async (ctx) => {
  const POINTS = 15;
  try {
    const { bookingId, rating, comment, isUpdate, userId } = ctx.request.body
    // 使用请求中的用户ID，如果未提供则默认为1（用于开发测试）
    const userIdToUse = userId || 1;

    const conn = await db.pool.getConnection()
    await conn.beginTransaction()

    try {
      if (isUpdate) {
        // 更新已有评价
        await conn.query(
          `UPDATE course_comments 
          SET rating = ?, content = ?
          WHERE booking_id = ?`,
          [rating, comment, bookingId]
        )
      } else {
        // 新增评价
        await conn.query(
          `INSERT INTO course_comments 
          (course_id, user_id, booking_id, rating, content) 
          SELECT b.course_id, ?, ?, ?, ? 
          FROM bookings b 
          WHERE b.id = ?`,
          [userIdToUse, bookingId, rating, comment, bookingId]
        )

        // 只有新增时才需要更新is_rated状态
        await conn.query(
          'UPDATE bookings SET is_rated = 1 WHERE id = ?',
          [bookingId]
        )

        // 新增评价时增加积分
        await addPoints(userIdToUse, POINTS, '填写评价奖励')
      }

      await conn.commit()
      ctx.body = { code: 200, message: '操作成功' }
    } catch (error) {
      await conn.rollback()
      throw error
    } finally {
      conn.release()
    }
  } catch (error) {
    console.error('操作失败:', error)
    ctx.status = 500
    ctx.body = { code: 500, message: '操作失败' }
  }
})

module.exports = router